package com.cloud.layuimini.controller;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Controller
public class SSE {

    ConcurrentHashMap<String, SseEmitter> sseMap = new ConcurrentHashMap<>();

    @RequestMapping(value="/sse/init/{username}", produces= MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter init(@PathVariable String username){
        SseEmitter sseEmitter = new SseEmitter();
        sseMap.put(username, sseEmitter);
        return sseEmitter;
    }

    @RequestMapping("/sse/send/{username}/{message}")
    @ResponseBody
    public String send(@PathVariable String username, @PathVariable String message) throws IOException {
        SseEmitter sseEmitter = sseMap.get(username);
        if (sseEmitter != null) {
            sseEmitter.send(message);
        } else {
            return "false";
        }
        return "success";
    }
}
